/**
 * 在数组查找是否有与给定数据一样的数据
 * @param {*} arr 要操作的数组
 * @param {*} key 数组里保存的数据
 * @param {*} val 要比较的数据
 * 没有一样的数据返回 -1,有一样的数据,返回数组里保存数据的下标,有就会返回>=0
 */
function inArray(arr, key, val) {//inArray(foundDevices, 'deviceId', device.deviceId)
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
function buf2hex(buffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
}
function buf2string(buffer) {
  var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  var str = ''
  for (var i = 0; i < arr.length; i++) {
    str += String.fromCharCode(arr[i])
  }
  return str
}
//字符串转Uint8Array
function str2ab1(str) {
  var bufView = new Uint8Array(str.length);// Uint8Array可换成其它
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  console.log(bufView)
  console.log('00000-3')
  return bufView;
}

//字符串转ArrayBuffer
function str2ab(str) {
  var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
  var bufView = new Uint8Array(buf);// Uint8Array可换成其它
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
//宽字节字符串转ArrayBuffer
function str2ab2(str) {
  var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
  var bufView = new Uint8Array(buf);// Uint8Array可换成其它
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    yeMianXuanZhe: 0,//页面按钮区
    gnMianXuanZhe: 0,//功能
    liangDuZhi: 5,//亮度
    ip: "",//socket服务器地址
    wifissid: "",//WIFI_SSID
    wifipass: "",//WIFI密码
    sbid: "未知设备",//设备ID
    sbDiZhi: "",//蓝牙设备 id
    deviceId: "",//蓝牙设备 id
    name: "CCC_XXN",//指定固定蓝牙名,才能连接
    chs: [],
    shuJuShuRu: "",
    shuJuShuRuPanDuan: false,
    kaiShiShiJian: "0:00",
    jieShiShiJian: "23:59"
  },
  onLoad() {
    this.chu_shi_hua();
  },

  shuJuShuRuH: function (e) {
    if (e.detail.value != "" && e.detail.value.length <= 20) {
      this.setData({
        shuJuShuRu: e.detail.value,
        shuJuShuRuPanDuan: true
      })
    }
  },
  //开始扫描
  openBluetoothAdapter() {
    //初始化蓝牙模块
    this.setData({
     // connected: true,
      yeMianXuanZhe: 1,
      //gnMianXuanZhe: 1,
    })
    console.log('kai shi sao miao 0001')
    wx.openBluetoothAdapter({
      success: (res) => { //接口调用成功的回调函数
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => { //接口调用失败的回调函数
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {//获取本机蓝牙适配器状态
    wx.getBluetoothAdapterState({//获取本机蓝牙适配器状态
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()//开始搜寻附近的蓝牙外围设备
        }
      }
    })
  },
  /**初始化蓝牙模块,接口调用成功的回调函数 */
  startBluetoothDevicesDiscovery() {//开始搜寻附近的蓝牙外围设备
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({ //开始搜寻附近的蓝牙外围设备
      allowDuplicatesKey: false, //是否允许重复上报同一设备
      success: (res) => { //接口调用成功的回调函数
        console.log('0000_startBluetoothDevicesDiscovery success', res)
        this.fa_xian_xin_she_bei()//调用搜索到新设备的事件的监听函数
      },
    })
  },
  stopBluetoothDevicesDiscovery() {//停止搜寻附近的蓝牙外围设备
    wx.stopBluetoothDevicesDiscovery()//停止搜寻附近的蓝牙外围设备
    console.log('停止搜寻附近的蓝牙外围设备01')
  },

  lian_jie_bt: function (deviceId1, name1) {//连接蓝牙低功耗设备
    console.log('00012')
    const deviceId = deviceId1
    const name = name1
    var tah = this
    wx.createBLEConnection({//连接蓝牙低功耗设备
      deviceId,//蓝牙设备 id
      success: (res) => {//接口调用成功的回调函数
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        if (sbDiZhi === deviceId) {
          try {
            var sbid1 = wx.getStorageSync('sbid')
            if (sbid1) {
              tah.data.sbid = sbid1
              this.setData({
                sbid,

              })
            }
          } catch (e) {
            sbid = "";
          }
        }
        this.getBLEDeviceServices(deviceId)////获取蓝牙低功耗设备所有服务 (service)
      }
    })
    this.stopBluetoothDevicesDiscovery()//停止搜寻附近的蓝牙外围设备
  },

  /**开始搜寻附近的蓝牙外围设备成功的回调 */
  fa_xian_xin_she_bei:function() {
    var self = this; // 保存 this 的引用 
    /**
     * deviceId = 蓝牙设备地址,类似:F4:EB:74:99:CF:22
     */
    wx.onBluetoothDeviceFound((res) => {//搜索到新设备的事件的监听函数

      res.devices.forEach(device => {//对数组中的每个元素执行指定的操作
        if (!device.name && !device.localName) {
          return
        }
        if (device.name === self.data.name) {
          const foundDevices = this.data.devices
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          const data = {}//这里可以指代this.data
          if (idx === -1) {
            /**
             * 将 `device` 对象添加到 `foundDevices` 数组中，并将其索引设置为 `foundDevices.length`,就是给数组的最后再增加一个成员
             * `device` 对象将作为数组的最后一个元素添加到 `foundDevices` 数组中。
             */
            data[`devices[${foundDevices.length}]`] = device
          } else {
            /**如果 `foundDevices` 数组中已经存在一个索引为 `foundDevices.length` 的元素，那么这个元素将被更新为 `device` 对象 */
            data[`devices[${idx}]`] = device
          }
          this.setData(data)//更新data
        }
      })
    })



  },
  /**开始搜寻附近的蓝牙外围设备成功的回调 */
  onBluetoothDeviceFound() {
    var self = this; // 保存 this 的引用 
    /**
     * deviceId = 蓝牙设备地址,类似:F4:EB:74:99:CF:22
     */
    wx.onBluetoothDeviceFound(function (devices) {//搜索到新设备的事件的监听函数
      var advertisData1 = null;
      var aa = null;
      if (devices.devices[0].deviceId) {
        console.log('aa000003')
        for (var i = 0; i < devices.devices.length; i++) {
          if (devices.devices[i].name === self.data.name) {
            wx.stopBluetoothDevicesDiscovery()//停止搜寻附近的蓝牙外围设备
            console.log(devices.devices[i].deviceId)
            console.log(devices.devices[i].name)
            self.data.deviceId = devices.devices[i].deviceId;//保存蓝牙设备地址
            self.lian_jie_bt(devices.devices[i].deviceId, devices.devices[i].name)
            break;
          }
        }
        console.log('aa000002')
      }
    })

  },



  createBLEConnection(e) {//连接蓝牙低功耗设备
    console.log('0001')
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({//连接蓝牙低功耗设备
      deviceId,//蓝牙设备 id
      success: (res) => {//接口调用成功的回调函数
        this.setData({
          yeMianXuanZhe: 2,
          gnMianXuanZhe: 6,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)////获取蓝牙低功耗设备所有服务 (service)
      }
    })
    this.stopBluetoothDevicesDiscovery()//停止搜寻附近的蓝牙外围设备
  },
  closeBLEConnection() {
    console.log('0002')
    wx.closeBLEConnection({//断开与蓝牙低功耗设备的连接。
      deviceId: this.data.deviceId//蓝牙设备 id
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {//获取蓝牙低功耗设备所有服务 (service)
    console.log('0003')
    wx.getBLEDeviceServices({//获取蓝牙低功耗设备所有服务 (service)
      deviceId,//蓝牙设备 id。需要已经通过 wx.createBLEConnection 建立连接
      success: (res) => {//接口调用成功的回调函数
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {//获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
    console.log('0004')
    wx.getBLEDeviceCharacteristics({//获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
      deviceId,//蓝牙设备 id。需要已经通过 wx.createBLEConnection 建立连接
      serviceId,//蓝牙服务 UUID。需要先调用 wx.getBLEDeviceServices 获取
      success: (res) => {//回调函数
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      console.log('0005')
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },

  writeBLECharacteristicValue() {//向蓝牙低功耗设备特征值中写入二进制数据
    //var buffer = stringToBytes("lokj,112.9089")
    if (this.data.shuJuShuRuPanDuan) {
      // 字符 转 ArrayBuffer
      let arrayBuffer1 = str2ab(this.data.shuJuShuRu);
      // 字符 转 Uint8Array
      let uint8Array = str2ab1(this.data.shuJuShuRu);
      console.log(uint8Array);
      // Uint8Array 转 ArrayBuffer
      let arrayBuffer = uint8Array.buffer
      console.log(arrayBuffer);

      wx.writeBLECharacteristicValue({//向蓝牙低功耗设备特征值中写入二进制数据
        deviceId: this._deviceId,//蓝牙设备 id
        serviceId: this._serviceId,//蓝牙特征对应服务的 UUID
        characteristicId: this._characteristicId,//蓝牙特征的 UUID
        value: arrayBuffer1,//写入的数据
      })
    }
  },
  closeBluetoothAdapter() {//关闭蓝牙模块。
    wx.closeBluetoothAdapter()//关闭蓝牙模块。
    this._discoveryStarted = false
  },
  // 事件处理函数  
  handleAction: function (event) {
    // 获取触发动作的组件的 ID  
    var self = this; // 保存 this 的引用 
    var componentId = event.currentTarget.id;
    // 根据组件 ID 进行相应的处理  
    if (componentId === 'wifiId') {
      // 组件1触发的动作处理  
      this.setData({
        gnMianXuanZhe: 1,
      })
      console.log('组件wifiId触发了动作');
    } else if (componentId === 'soctId') {
      this.setData({
        gnMianXuanZhe: 2,
      })
      console.log('组件soctId触发了动作');
    } else if (componentId === "liangDuId") {
      this.setData({
        gnMianXuanZhe: 3,
      })
      console.log('liangDuId组件触发了动作');
    } else if (componentId === "sheBeiId") {
      this.setData({
        gnMianXuanZhe: 4,
      })
      try {
        wx.setStorageSync('weiXinMing', res.userInfo.nickName) //同步保存数据
      } catch (e) {
        //
      }
      console.log('liangDuId组件触发了动作');
    } else if (componentId === "shengXiaoId") {
      this.setData({
        gnMianXuanZhe: 5,
      })
      console.log('liangDuId组件触发了动作');
    } else {
      console.log('其他组件触发了动作');
    }
  },
  // 确定事件处理函数  
  que_ding_chu_li: function (event) {
    // 获取触发动作的组件的 ID  
    var self = this; // 保存 this 的引用 
    var componentId = event.currentTarget.id;
    var ls = "";
    // 根据组件 ID 进行相应的处理  
    if (componentId === 'wifiIDOK') {
      // 组件1触发的动作处理  
      ls = `{\"id\":${self.data.sbid},\"lx\":14,\"ips\":${self.data.wifissid},\"vvs\":${self.data.wifipass}}`
      this.bt_fa_song(ls)
    } else if (componentId === 'SocketTxtIDOK') {
      ls = `{\"id\":${self.data.sbid},\"lx\":15,\"ips\":\"ip\",\"vvs\":${self.data.ip}}`
      this.bt_fa_song(ls)
    } else if (componentId === "liangDuHuanKuaiIdOK") {
      ls = `{\"id\":${self.data.sbid},\"lx\":33,\"ksi\":${self.data.liangDuZhi}}`
      this.bt_fa_song(ls)
    } else if (componentId === "sbidTxtIDOK") {
      try {
        wx.setStorageSync('sbid', self.data.sbid) //同步保存数据
      } catch (e) {
        console.log('sbid保存未知错误');
      }
      console.log('liangDuId组件触发了动作');
    } else {
      console.log('其他组件触发了动作');
    }
  },

  sheng_xiao_shi_jian: function () {
    let ls = ""
    let kaiShi = this.data.kaiShiShiJian.split(":")
    let jieShu = this.data.jieShiShiJian.split(":")
    let kaiShiShi = Number(kaiShi[0])
    let kaiShiFen = Number(kaiShi[1])
    let jiwShuShi = Number(jieShu[0])
    let jiwShuFen = Number(jieShu[1])
    ls = `{\"id\":${this.data.sbid},\"lx\":31,\"ksi\":${kaiShiShi},\"jsi\":${kaiShiFen}}`
    this.bt_fa_song(ls)
    // 延时500毫秒
    setTimeout(function () {
      ls = `{\"id\":${this.data.sbid},\"lx\":32,\"ksi\":${jiwShuShi},\"jsi\":${jiwShuFen}}`
      this.bt_fa_song(ls)
    }, 500);
    //console.log(`开始:${kaiShiShi}:${kaiShiFen}--结束:${jiwShuShi}:${jiwShuFen}`)
  },

  bt_fa_song: function (str) {//向蓝牙低功耗设备特征值中写入二进制数据
    // 字符 转 ArrayBuffer
    let arrayBuffer1 = str2ab(str);
    wx.writeBLECharacteristicValue({//向蓝牙低功耗设备特征值中写入二进制数据
      deviceId: this._deviceId,//蓝牙设备 id
      serviceId: this._serviceId,//蓝牙特征对应服务的 UUID
      characteristicId: this._characteristicId,//蓝牙特征的 UUID
      value: arrayBuffer1,//写入的数据
    })
  },


  liang_du: function (e) {
    this.setData({
      liangDuZhi: e.detail.value
    })
    console.log(e.detail.value);
  },
  she_bei_id(e) {
    // 监听文本框输入变化，更新 data 中的值  
    this.setData({
      sbid: e.detail.value
    });
  },
  /*
  dan_xuan_shi_jian_duan(e){
    let shiJianDanXuan = e.detail.value
    this.setData({
      shiJianDanXuan:shiJianDanXuan
    })
    console.log('携带数据为：', e.detail.value)
  },     
  */
  xuan_zhe_kai_shi_shi_jian(e) {
    //console.log(e.detail.value)
    this.setData({
      kaiShiShiJian: e.detail.value
    })
    //let time = e.detail.value.split(":");
    //console.log(`${time[0]}  小时,  ${time[1]}  分`);
  },
  xuan_zhe_jie_su_shi_jian(e) {
    this.setData({
      jieShiShiJian: e.detail.value
    })
  },

  chu_shi_hua: function () {
    var that = this
    //wx.setStorageSync('weiXinMing', res.userInfo.nickName) //同步保存数据
    try {
      var sbDiZhi = wx.getStorageSync('sbDiZhi')
      if (deviceId && sbid) {
        that.data.sbDiZhi = sbDiZhi;
      }
    } catch (e) {
      sbDiZhi = "";
    }
  }











})